//
//  SubmitOrderVC.m
//  UHealth
//
//  Created by hanyou on 15/3/23.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "SubmitOrderVC.h"
#import "AFNetworking.h"
#import "iToast.h"

#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "APAuthV2Info.h"

#import "OrderInfoVC.h"


@interface SubmitOrderVC ()

@property (nonatomic,strong) NSDictionary   *serviceDic;
@property (nonatomic,strong) UITextField    *f;
@property (nonatomic,strong) UILabel        *allL;

@property (nonatomic,strong) UIButton       *buyBtn;

@end

@implementation SubmitOrderVC

- (id)initWithDic:(NSDictionary *)dic
{
    _serviceDic = dic;
    self = [super init];
    if (self) {
        // Custom initialization
        self.view.backgroundColor = kBacColor;
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NavView *nav = [[NavView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, kNavHeight) andTitleStr:kLocal(@"submitOrder") andVC:self];
    [self.view addSubview:nav];
    
    UILabel *fwL = [[UILabel alloc]initWithFrame: CGRectMake(15, kNavHeight+15, WIDTH-30, 30)];
    fwL.text = [NSString stringWithFormat:@"%@",_serviceDic[@"shop_name"]];
    [self.view addSubview:fwL];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(15, kNavHeight+45, WIDTH-30, 1)];
    line.backgroundColor = kBlueColor;
    [self.view addSubview:line];
    
    UILabel *priL = [[UILabel alloc]initWithFrame: CGRectMake(15, kNavHeight+45, WIDTH-30, 30)];
    priL.text = [NSString stringWithFormat:@"%@:    %@",kLocal(@"unit_price"),_serviceDic[@"saleprice"]];
    [self.view addSubview:priL];
    
    UILabel *countL = [[UILabel alloc]initWithFrame: CGRectMake(15, kNavHeight+75, 60, 30)];
    countL.text = [NSString stringWithFormat:@"%@:",kLocal(@"total_num")];
    [self.view addSubview:countL];
    
    _f = [[UITextField alloc]initWithFrame:CGRectMake(70, kNavHeight+75, WIDTH-80, 30)];
    _f.keyboardType = UIKeyboardTypeNumberPad;
    _f.text = @"1";
    [self.view addSubview:_f];
    
    _allL = [[UILabel alloc]initWithFrame: CGRectMake(15, kNavHeight+105, WIDTH-30, 30)];
    _allL.text = [NSString stringWithFormat:@"%@:   %@",kLocal(@"total_price"),_serviceDic[@"saleprice"]];
    [self.view addSubview:_allL];
    
    for (int i = 0; i < 3; i++) {
        UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(15, kNavHeight+75 + i*30, WIDTH-30, 0.5)];
        line1.backgroundColor = [UIColor grayColor];
        [self.view addSubview:line1];
    }
    
    UILabel *jsL = [[UILabel alloc]init];
    jsL.text = [NSString stringWithFormat:@"%@: %@",kLocal(@"description"),_serviceDic[@"js"]];
    jsL.numberOfLines = 0;
    CGSize size =[jsL.text boundingRectWithSize:CGSizeMake(WIDTH,2000) options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:jsL.font} context:nil].size;
    jsL.frame =  CGRectMake(15,kNavHeight+145, WIDTH-30, size.height);
    [self.view addSubview:jsL];
    
    
    _buyBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _buyBtn.frame = CGRectMake(15, kNavHeight+155+jsL.frame.size.height+10, WIDTH-30, 40);
    [_buyBtn.layer setMasksToBounds:YES];
    [_buyBtn.layer setCornerRadius:1.0];//设置矩形是个圆角半径
    _buyBtn.backgroundColor = kBlueColor;
    [_buyBtn setTitle:kLocal(@"submitOrder") forState:UIControlStateNormal];
    [_buyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_buyBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    _buyBtn.tag = 1;
    [self.view addSubview:_buyBtn];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
    
    float a = [_serviceDic[@"saleprice"] floatValue];
    int c = [_f.text intValue];
    _allL.text = [NSString stringWithFormat:@"%@:   %.2f",kLocal(@"total_price"),a*c];
}

-(void)btnClick:(UIButton *)btn
{
    int c = [_f.text intValue];
    if(!c){
        [[iToast makeText:kLocal(@"input_num")] show];
        return;
    }
    if(!kNetID){
        [[iToast makeText:kLocal(@"notLogin")] show];
        return;
    }
    if (!kNetIsOK) {
        [[iToast makeText:kLocal(@"netNoOk")] show];
        return ;
    }
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = 5;
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
    NSString *postStr = [NSString stringWithFormat:@"%@/action/json/shop.jsp?",kBaseUrl];
    NSDictionary *parameters = @{@"action": @"createorder",
                                 @"userid":[NSString stringWithFormat:@"%ld",(long)kNetID],
                                 @"shopid":_serviceDic[@"id"],
                                 @"buynum":_f.text};
    
    [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //kDebug(@"Success: %@", operation.responseString);
        BOOL type = [[responseObject objectForKey:@"type"] boolValue];
        if(type){//成功
            //{"order_id":1288,"saleprice":0.01,"gys":"春雨医生","shop_name":"春雨医生两年服务","order_no":"511772842","order_time":"2015-02-11 11:45:16","type":true,"msg":"提交成功"}
            _buyBtn.enabled = NO;
            [_buyBtn setTitle:kLocal(@"commited") forState:UIControlStateNormal];
            _buyBtn.backgroundColor = [UIColor grayColor];
            
            if (/* DISABLES CODE */ (YES)) {
                OrderInfoVC *or = [[OrderInfoVC alloc]initWithDic:@{@"appfile":_serviceDic[@"appfile"],
                                                                    @"shop_name":responseObject[@"shop_name"],
                                                                    @"saleprice":responseObject[@"saleprice"],
                                                                    @"order_status":@"",
                                                                    @"order_no":responseObject[@"order_no"],
                                                                    @"add_time":responseObject[@"order_time"],
                                                                    @"js":_serviceDic[@"js"],
                                                                    @"orderid":responseObject[@"order_id"],
                                                                    @"buynum":_f.text,
                                                                    }];
                [self presentViewController:or animated:YES completion:nil];
                
            }else{//取消
                [self beforePayWithDic:@{@"orderid":responseObject[@"order_id"],
                                         @"order_no":responseObject[@"order_no"],
                                         @"shop_name":responseObject[@"shop_name"],
                                         @"js":_serviceDic[@"js"],
                                         @"saleprice":responseObject[@"saleprice"]}];
            }
            
        }else{
            
        }
        [[iToast makeText:[responseObject objectForKey:@"msg"]] show];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        kDebug(@"Error: %@", error);
        [[iToast makeText:kLocal(@"netError")] show];
    }];
}


//支付前  取消
-(void)beforePayWithDic:(NSDictionary *)orderDic
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = 5;
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
    NSString *postStr = [NSString stringWithFormat:@"%@/action/json/shop.jsp?",kBaseUrl];
    NSDictionary *parameters = @{@"action": @"orderpay",
                                 @"userid":[NSString stringWithFormat:@"%ld",(long)kNetID],
                                 @"orderid":orderDic[@"orderid"],
                                 @"pay_mode":@"1"};
    
    [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //        kDebug(@"Success: %@", operation.responseString);
        BOOL type = [[responseObject objectForKey:@"type"] boolValue];
        if(type){//成功
            
            [self payWithDic:orderDic];
        }else{
        }
        [[iToast makeText:[responseObject objectForKey:@"msg"]] show];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        kDebug(@"Error: %@", error);
        [[iToast makeText:kLocal(@"netError")] show];
    }];
}
//支付 取消
-(void)payWithDic:(NSDictionary *)orderDic
{
    NSString *tradeNO = [NSString stringWithFormat:@"%@",orderDic[@"order_no"]];
    NSString *productName = [NSString stringWithFormat:@"%@",orderDic[@"shop_name"]];
    NSString *productDescription = [NSString stringWithFormat:@"%@",orderDic[@"js"]];
    float price = [orderDic[@"saleprice"] floatValue];
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = kpartner;
    order.seller = kseller;
    order.tradeNO = tradeNO; //订单ID（由商家自行制定）
    order.productName = productName; //商品标题
    order.productDescription = productDescription; //商品描述
    order.amount = [NSString stringWithFormat:@"%.2f",price]; //商品价格
    order.notifyURL =  knotifyURL; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在Info.plist定义URL types
    NSString *appScheme = @"alisdkdemo";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    //    kDebug(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(kprivateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            kDebug(@"reslut = %@",resultDic);
        }];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
